<!-- =========================================================================================
    Description: Login Page
    Author: Pixinvent
========================================================================================== -->

<template>
  <div
    class="h-screen flex w-full vx-row no-gutter items-center justify-center"
    id="page-login"
    :style="{
      background: 'url(' + backgroundImageUrl+ ')',
      backgroundPosition: 'center',
      backgroundSize: 'cover',
      backgroundRepeat: 'no-repeat'
    }"
  >
    <div class="vx-col sm:w-1/2 md:w-1/2 lg:w-3/4 xl:w-3/5 sm:m-0 m-4">
      <vx-card>
        <div slot="no-body" class="full-page-bg-color">
          <div class="vx-row no-gutter justify-center items-center">
            <div class="vx-col hidden lg:block lg:w-1/2">
              <img :src="illustrationImageUrl" alt="login" class="mx-auto" />
            </div>
            <div class="login-wrapper vx-col sm:w-full md:w-full lg:w-1/2 d-theme-dark-bg">
              <div class="account-wrapper p-8" v-show="!isScan">
                <div class="toggle-account" @click="showScan"></div>
                <div class="vx-card__title">
                  <h4>账号登录</h4>
                  <p>欢迎回来，请登录您的账号</p>
                </div>
                <div class="input-item">
                  <vs-input
                    data-vv-validate-on="blur|input"
                    v-validate="'required|min:3'"
                    name="账号"
                    placeholder="账号"
                    icon="icon icon-user"
                    icon-pack="feather"
                    v-model="account"
                    class="w-full mt-4 no-icon-border"
                  />
                  <span class="text-danger text-sm">
                    {{
                    errorBags.first("账号")
                    }}
                  </span>
                </div>
                <div class="input-item">
                  <vs-input
                    data-vv-validate-on="blur||input"
                    v-validate="'required|min:6|max:10'"
                    type="password"
                    placeholder="密码"
                    name="密码"
                    icon="icon icon-lock"
                    icon-pack="feather"
                    v-model="password"
                    class="w-full no-icon-border"
                  />
                  <span class="text-danger text-sm">
                    {{
                    errorBags.first("密码")
                    }}
                  </span>
                </div>
                <div class="input-item">
                  <div class="verifyCode-wrapper flex">
                    <vs-input
                      data-vv-validate-on="blur|input"
                      v-validate="'required'"
                      name="验证码"
                      placeholder="验证码"
                      icon="icon icon-link"
                      icon-pack="feather"
                      v-model="verifyCode"
                      class="no-icon-border verifyCode-input md:w-2/3"
                    />
                    <vs-input
                      class="verifyCode ml-2 md:w-1/3"
                      disabled="true"
                      v-model="verifyCode_back"
                    />
                  </div>
                  <span class="text-danger text-sm">
                    {{
                    errorBags.first("验证码")
                    }}
                  </span>
                </div>
                <div class="flex flex-wrap justify-between mb-4">
                  <vs-checkbox v-model="checkbox_remember_me">记住密码</vs-checkbox>
                  <span class="text-primary" @click="forgotPassword">忘记密码？</span>
                </div>
                <vs-button
                  class="w-full bg-primary mt-5"
                  :disabled="!validateForm"
                  @click="login()"
                >登录</vs-button>
              </div>
              <div class="scan-wrapper p-8" v-show="isScan">
                <div class="toggle-code" @click="toggleScan"></div>
                <div class="vx-card__title mb-4">
                  <h4 class="mb-4">扫二维码登录</h4>
                  <p>手机扫码，安全登录</p>
                </div>
                <div class="QRcode-wrapper flex justify-center mb-12 mt-12">
                  <div v-show="isShowCodeCove" class="coveQrcode">
                    <span>二维码已失效</span>
                    <vs-button size="small" class="mt-3" @click="showScan">刷新</vs-button>
                  </div>
                  <div id="qrcode"></div>
                </div>
                <div class="app-download-wrapper flex justify-center items-center">
                  <img src="../../assets/images/pages/login/scan.png" width="30" height="30" alt />
                  <div class="app-download ml-6">
                    <p class="cursor-pointer" @click="$router.push('/pages/AppDownload')">
                      下载安装
                      <span class="text-primary">瑞智云官方App</span>
                    </p>
                    <p>扫一扫登录</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </vx-card>
    </div>
  </div>
</template>

<script>
import projectConfig from "@/../public/project.config.js";
import { getCookie, setCookie } from "@/init/cookie.js";
import md5 from "js-md5";
import QRCode from "qrcodejs2";
// import PROJECT_CONFIG from "@/config/switch";
import base from "@/api/base";
export default {
  data() {
    return {
      repeatSubmit: true,
      isScan: false,
      account: "",
      password: "",
      verifyCode: "",
      verifyCode_back: "abcd",
      checkbox_remember_me: false,
      baseUrl: process.env.BASE_URL,
      LoginQrCode: "",
      time: 60,
      isShowCodeCove: false,
      setTimeOutSign: "",
      loginMessage: ""
      // illustrationImageUrl: process.env.BASE_URL + '@/assets/images/pages/login/login.png',
      // backgroundImageUrl: '',
    };
  },
  computed: {
    validateForm() {
      return (
        !this.errorBags.any() &&
        this.account != "" &&
        this.password != "" &&
        this.verifyCode!=""
      );
    },
    illustrationImageUrl() {
      return this.baseUrl + projectConfig.loginImg;
    },
    backgroundImageUrl() {
      return this.baseUrl + projectConfig.loginBg;
    }
  },
  methods: {
    //登录
    login(code) {
      this.repeatSubmit = false;
      //存储权限配置资源树参数
      localStorage.setItem("appkey", PROJECT_CONFIG.appkey);
      let userInfo = {
        username: this.account,
        password: md5(this.password)
      };
      if (this.LoginQrCode && this.isScan) {
        userInfo["LoginQrCode"] = this.LoginQrCode;
      } else {
        delete userInfo["LoginQrCode"];
        if (
          this.verifyCode.toLowerCase() != this.verifyCode_back.toLowerCase()
        ) {
          this.$vs.notify({
            text: "验证码输入错误，请重新输入！",
            color: "danger"
          });
          this.verifyCode = "";
          return;
        }
      }
      //登录
      this.$api.login
        .login(userInfo)
        .then(res => {
          if (res.data.success) {
            clearTimeout(this.setTimeOutSign);
            let loginInfo = res.data.data || {};
            loginInfo.userid = loginInfo.userId;
            localStorage.setItem("userInfo", JSON.stringify(userInfo));
            sessionStorage.setItem("loginInfo", JSON.stringify(res.data.data)); //用于集成页面获取userId
            this.$vs.notify({ text: "登录成功！", color: "success" });
            localStorage.setItem("token", res.data.token);
            this.$store.dispatch("updateToken", res.data.token);
            if (this.$route.query.to) {
              this.$router.push({ path: this.$route.query.to });
            } else {
              this.$router.push("/log-manage/Log");
            }
            // 记住密码,存储登录信息
            this.setUserInfo();
          }
        })
        .catch(e => {
          this.account = "";
          this.password = "";
          this.verifyCode = "";
          if (!code) {
            this.loginMessage = "";
            this.$vs.notify({ text: `${e.data.message}`, color: "danger" });
          } else {
            this.loginMessage = "当前用户未扫码";
          }
        });
    },
    // 储存表单信息
    setUserInfo() {
      // 判断用户是否勾选记住密码，如果勾选，向cookie中储存登录信息，
      // 如果没有勾选，储存的信息为空
      if (this.checkbox_remember_me) {
        setCookie("account", this.account);
        setCookie("password", this.password);
        setCookie("checkbox_remember_me", this.checkbox_remember_me);
      } else {
        setCookie("account", "");
        setCookie("password", "");
        setCookie("checkbox_remember_me", "");
      }
    },
    //忘记密码
    forgotPassword() {
      this.$router.push("/pages/ForgotPassword");
    },
    //生成二维码
    qrcode(qrcodeStr) {
      let qrcode = new QRCode("qrcode", {
        width: 130,
        height: 130,
        text: qrcodeStr, // 二维码地址
        colorDark: "#000",
        colorLight: "#fff"
      });
      return qrcode;
    },
    //显示二维码
    showScan() {
      if (!this.isScan) {
        this.isScan = !this.isScan;
      }
      this.isShowCodeCove = false;
      document.getElementById("qrcode").innerHTML = "";
      //获取二维码,二维码有效期1分钟
      this.$api.login
        .getQRCode()
        .then(res => {
          this.LoginQrCode = res.data;
          this.qrcode(res.data);
          this.waitScan();
        })
        .catch(e => {
          // console.log(e);
        });
    },
    //等待APP扫描二维码
    waitScan() {
      this.time = 60;
      this.timer();
    },
    //等待APP扫描二维码,60S倒计时
    timer() {
      if (this.time > 0) {
        this.time--;
        this.login("code");
        this.setTimeOutSign = setTimeout(this.timer, 1000);
      } else {
        this.time = 0;
        this.isShowCodeCove = true;
      }
    },
    //切换登录方式
    toggleScan() {
      this.isScan = !this.isScan;
      clearTimeout(this.setTimeOutSign);
    },
    //登录页配置
    getloginPageConfig() {
      let urlStr = projectConfig.urlCode;
      urlStr = urlStr.split("login/");
      this.$api.login.getLoginConfig({ code: urlStr[1] }).then(res => {
        let data = res.data.data;
        let logo = "";
        if (data.background.indexOf("http") != -1) {
          this.backgroundImageUrl = data.background;
          let getIp = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;
          let ip = getIp.exec(this.backgroundImageUrl);
          this.backgroundImageUrl = this.backgroundImageUrl.replace(
            ip,
            "rziot.net"
          );
        } else {
          let backgroundFileId = JSON.parse(data.background)[0].fileId;
          this.backgroundImageUrl = `${base.DOWNLOADURL}?fileId=${backgroundFileId}`;
        }
        if (data.logo.indexOf("http") != -1) {
          logo = data.logo;
        } else {
          let logoFileId = JSON.parse(data.logo)[0].fileId;
          logo = `${base.DOWNLOADURL}?fileId=${logoFileId}`;
        }
        if (data.paint.indexOf("http") != -1) {
          this.illustrationImageUrl = data.paint;
        } else {
          let paintFileId = JSON.parse(data.paint)[0].fileId;
          this.illustrationImageUrl = `${base.DOWNLOADURL}?fileId=${paintFileId}`;
        }

        localStorage.setItem("projectName", data.title);
        localStorage.setItem("logoSrc", logo);
      });
    }
  },
  mounted() {
    //获取验证码
    this.$api.login.getCaptcha().then(res => {
      this.verifyCode_back = res.data.data;
    });
  },
  created() {
    // this.getloginPageConfig();
    // 在页面加载时从cookie获取登录信息
    let account = getCookie("account");
    let password = getCookie("password");
    let remenberMe = getCookie("checkbox_remember_me");
    // 如果存在赋值给表单，并且将记住密码勾选
    if (remenberMe) {
      this.account = account;
      this.password = password;
      this.checkbox_remember_me = true;
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/scss/baseColor.scss";
#page-login {
  .social-login {
    display: none !important;
    .bg-facebook {
      background-color: #1551b1;
    }
    .bg-twitter {
      background-color: #00aaff;
    }
    .bg-google {
      background-color: #4285f4;
    }
    .bg-github {
      background-color: #333;
    }
  }
  .login-wrapper {
    position: relative;
    .account-wrapper {
      position: relative;
      height: 28rem;
      .toggle-account {
        position: absolute;
        top: 0;
        right: 0px;
        width: 50px;
        height: 50px;
        background: url("../../assets/images/pages/login/toggle_account.png")
          no-repeat;
        background-size: 100% 100%;
        &:before {
          content: "";
          cursor: default;
          position: absolute;
          width: 67px;
          height: 67px;
          top: 14px;
          left: -31px;
          background-color: #fff;
          -webkit-transform: rotate(45deg);
          -ms-transform: rotate(45deg);
          transform: rotate(45deg);
        }
        .verifyCode-input {
          display: inline-block;
          margin-right: 0.8rem;
        }
      }
      .verifyCode {
        .vs-input--input.normal {
          background: #fff;
          text-align: center;
          padding: 6px;
          color: $mainColor;
          font-size: 20px;
          letter-spacing: 5px;
        }
      }
    }
    .scan-wrapper {
      position: relative;
      height: 28rem;
      .toggle-code {
        position: absolute;
        top: 0;
        right: 0px;
        width: 50px;
        height: 50px;
        background: url("../../assets/images/pages/login/toggle_code.png")
          no-repeat;
        background-size: 100% 100%;
        &:before {
          content: "";
          cursor: default;
          position: absolute;
          width: 67px;
          height: 67px;
          top: 14px;
          left: -31px;
          background-color: #fff;
          -webkit-transform: rotate(45deg);
          -ms-transform: rotate(45deg);
          transform: rotate(45deg);
        }
      }
    }
  }
  .loginTitle {
    position: absolute;
    top: 0;
    left: 0;
    display: flex;
    justify-content: start;
    align-items: center;
  }
  .coveQrcode {
    width: 130px;
    height: 130px;
    position: absolute;
    background-color: rgba(0, 0, 0, 0.637);
    text-align: center;
    > span {
      color: #fff;
      display: inline-block;
      margin-top: 2.5rem;
    }
  }
}
.input-item {
  height: 4.4rem;
}
</style>
